﻿#region Copyright (c) 2010 R. Uittenbosch
/*
* Copyright (C) 2010 R. Uittenbosch
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
* associated documentation files (the "Software"), to deal in the Software without restriction, including 
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 
* following conditions:
* 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net;
using System.IO;
using System.Drawing;

namespace LinkedService.Mobile
{

  /// <summary>
  /// Singleton implementation to retrieve images from the web
  /// uses a different thread to retrieve the pictures
  /// </summary>
  public class ProfileImageLoader
  {

    public static Bitmap LoadPicture(string url)
    {
      HttpWebRequest wreq = null;
      HttpWebResponse wresp = null;
      Stream mystream = null;
      Bitmap bmp = null;

      try
      {
        wreq = (HttpWebRequest)WebRequest.Create(url);
        wreq.AllowWriteStreamBuffering = false;
        wreq.Timeout = 2000;
        wresp = (HttpWebResponse)wreq.GetResponse();

        if ((mystream = wresp.GetResponseStream()) != null)
          bmp = new Bitmap(mystream);
      }
      catch (Exception e)
      {
        // We do not want to an exception to be raised...
        Console.WriteLine(e.ToString());
      }
      finally
      {
        if (wreq != null)
          wreq = null;
        if (mystream != null)
          mystream.Close();
        if (wresp != null)
          wresp.Close();
      }

      return (bmp);

    }

    /// <summary>
    /// A list of items to retrieve
    /// </summary>
    private List<ProfileImage> _pictures;

    /// <summary>
    /// Busy indicator
    /// </summary>
    private bool _busy = false;

    // Make singleton
    private static ProfileImageLoader _instance = null;

    /// <summary>
    /// Get the current instance from memory
    /// </summary>
    public static ProfileImageLoader Instance
    {
      get
      {
        if (_instance == null)
          _instance = new ProfileImageLoader();
        return _instance;
      }
    }

    /// <summary>
    /// Constructor
    /// </summary>
    public ProfileImageLoader()
    {
        _pictures = new List<ProfileImage>();
    }

    /// <summary>
    /// Load an image in a different thread
    /// </summary>
    /// <param name="objectstate"></param>
    private void LoadImage(Object objectstate)
    {
      // Find an item that is not loaded yet.
      ProfileImage cur = _pictures.Find(p => p.Loaded == false);
      if (cur != null)
      {
        // If found, get it from the web.
        cur.Picture = ProfileImageLoader.LoadPicture(cur.PictureUrl);

        // If the picture contains data, mark it as loaded
        if (cur.Picture != null)
          cur.Loaded = true;
      }

      // Is there anything else in the list, load the next, otherwise set busy flag to false
      if (_pictures.Exists(p => p.Loaded == false))
        LoadNext();
      else
        _busy = false;

    }

    /// <summary>
    /// (Try to) Load a new item
    /// </summary>
    private void LoadNext()
    {
      _busy = true;
      // Queue the item in the threadpool
      ThreadPool.QueueUserWorkItem(new WaitCallback(LoadImage),null);    
    }

    /// <summary>
    /// Create a profileimage from an url
    /// </summary>
    /// <param name="pictureUrl"></param>
    /// <returns></returns>
    public ProfileImage Create(string pictureUrl)
    {
      // If already loaded, return it, otherwise mark it for loading
      if (!_pictures.Exists(c => c.PictureUrl == pictureUrl))
        return Load(new ProfileImage() { PictureUrl = pictureUrl, Loaded = false });
      else
        return _pictures.Find(c => c.PictureUrl == pictureUrl);
    }

    /// <summary>
    /// Mark an image for loading.
    /// </summary>
    /// <param name="p"></param>
    /// <returns></returns>
    private ProfileImage Load(ProfileImage p)
    {
      _pictures.Add(p);
      // In case it's not already loading anything else, start the process.
      if (_busy == false)
        LoadNext();

      // Return a reference to the image
      return p;
    }
  }
}
